'use strict';
var React=require( 'react');
var reactDom=require( 'react-dom/server');
var reactRedux=require('react-redux');
var configureStore=require('../public/javascripts/stores/index.js');
var NewsViewer=require( '../public/javascripts/containers/NewsViewer');
var Provider=reactRedux.Provider;
const store = configureStore();
var utils=require('../public/javascripts/common/utils');
var cac=utils.cac;
var http = require('http');
var querystring = require('querystring');
var actions=require('../public/javascripts/actions/news');
const receiveDetail = cac(actions.GET_SINGLE_NEWS, 'data');
exports.RenderFunc=(id, renderCallBack)=>{
    var contents = querystring.stringify({
        id:id
    });

    var options = {
        host: 'www.tngou.net',
        path: '/api/top/show?'+contents
    };

    http.get(options, function(res) {
        var result="";
        res.setEncoding('utf8');
        res.on("data", function (chunk) {
            // 数据比较多时会分多次到达，此处累加数据
            result += chunk;
        });
        res.on('end', function (data) {
            //所有数据回传成功后渲染
            result=JSON.parse(result);
            if(result.status) {
                store.dispatch(receiveDetail(result));
                if(renderCallBack) {
                    var main = reactDom.renderToString(
                        <Provider store={store}>
                            <NewsViewer/>
                        </Provider>
                    );
                    var initializeStore = JSON.stringify(store.getState());
                    renderCallBack(main,initializeStore);
                }
            }
        });
    });

};
